<?php

namespace App\Http\Middleware;

use App\Helper\ErrorCode;
use Closure;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Redis;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     * @throws TokenMismatchException
     */
    public function handle($request, Closure $next)
    {
        if(env('APP_ENV')=='production'){
            if(abs(time()-$request->input('timestamp'))>10){
                throw new TokenMismatchException('token error',ErrorCode::TOKEN_ERROR);
            }
            if(Redis::get('user_token'.$request->input('u')) != $request->input('token')){
                throw new TokenMismatchException('token error',ErrorCode::TOKEN_ERROR);
            }
            $param = $request->except(['sign']);
            ksort($param);
            $sign = '';
            foreach($param as $k=>$v){
                $sign .=  '&'.$k.'='.$v;
            }
            $sign .= $param['timestamp'] % 17351 ;
            $sign = md5(ltrim($sign,'&'));
            if($sign <> $request->input('sign')){
                throw new TokenMismatchException('token error',ErrorCode::TOKEN_ERROR);
            }

        }
        return $next($request);
    }
}
